package org.mokusakura.web.servlet;

import org.mokusakura.constant.ServletNameConstant;
import org.mokusakura.constant.ServletUrlConstant;
import org.mokusakura.constant.SessionAttributeKeyConstant;
import org.mokusakura.persistence.Util.VerifyCodeGenerator;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author MokuSakura
 */
@WebServlet(name = ServletNameConstant.VERIFY_CODE_SERVLET_NAME, urlPatterns = {ServletUrlConstant.VERIFY_CODE_SERVLET_URL})
public class VerifyCodeServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpeg";
    private static final String HEADER_PRAGMA = "Pragma";
    private static final String HEADER_CACHE_CONTROL = "Cache-Control";
    private static final String STRING_NO_CACHE = "No-cache";
    private static final int INT_NO_CACHE = 0;
    private static final int WIDTH = 80;
    private static final int HEIGHT = 20;
    private static final String HEADER_EXPIRES = "Expires";
    private static final String FORMAT_NAME = "JPEG";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // response with image
        resp.setContentType(CONTENT_TYPE);
        // no cache
        resp.setHeader(HEADER_PRAGMA, STRING_NO_CACHE);
        resp.setHeader(HEADER_CACHE_CONTROL, STRING_NO_CACHE);
        resp.setDateHeader(HEADER_EXPIRES, INT_NO_CACHE);

        OutputStream outputStream = resp.getOutputStream();
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        String verifyCode = VerifyCodeGenerator.GenerateVerifyCode(bufferedImage);
        req.getSession().setAttribute(SessionAttributeKeyConstant.CORRECT_VERIFY_CODE, verifyCode);
        ImageIO.write(bufferedImage, FORMAT_NAME, outputStream);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

}
